<template>
    <div>
        <group title="作者">
            <x-input name="name" v-model="formData.author" placeholder="请输入作者姓名或昵称" :max="15"></x-input>
        </group>

        <group title="性别">
            <button-tab v-model="formData.sex">
                <button-tab-item>男</button-tab-item>
                <button-tab-item>女</button-tab-item>
            </button-tab>
        </group>

        <group title="联系电话">
            <x-input name="mobile" v-model="formData.phone" placeholder="请输入手机号码" keyboard="number" is-type="china-mobile"></x-input>
        </group>

        <group title="邮箱">
            <x-input name="email" v-model="formData.email" placeholder="请输入邮箱地址" is-type="email"></x-input>
        </group>

        <group title="自我介绍&作品介绍">
            <x-textarea :max="20" v-model="formData.intro" placeholder="说点什么吧~"></x-textarea>
        </group>

        <group title="图片上传">
            <grid :cols="3" :show-lr-borders="false">
                <grid-item label="已上传" v-for="i in imgCount" :key="i" @on-item-click="show(i - 1)" s="i">
                    <img slot="icon" :src="imgList[i - 1].src" class="previewer-img">

                </grid-item>
                <grid-item label="点击添加" v-if="uploadImgBtn">
                    <input id="uploaderInput" class="uploader" type="file" accept="image/*" @change="upload" multiple>

                    <img slot="icon" src="/static/imgs/upload.png">
                </grid-item>
            </grid>
        </group>

        <group>
            <flexbox>
                <flexbox-item>
                    <x-button type="default" @click.native="resetForm" :disabled="resetBtnDisabled">重置</x-button>
                </flexbox-item>
                <flexbox-item>
                    <x-button type="primary" @click.native="formSubmit" :text="submitBtnText" :disabled="submitBtnDisabled"></x-button>
                </flexbox-item>
            </flexbox>
        </group>

        <div v-transfer-dom>
            <previewer :list="imgList" ref="previewer" :options="options"></previewer>
            <!--<previewer ref="previewer" :list="imgList" :options="options">-->
                <!--<template slot="button-after">-->
                    <!--<span class="previewer-delete-icon-box">-->
                      <!--<img src="/static/imgs/upload.png" width="22" height="22" class="previewer-delete-icon" @click.prevent.stop="removeImg">-->
                    <!--</span>-->
                <!--</template>-->
            <!--</previewer>-->
        </div>

        <div v-transfer-dom>
            <loading :show="loadingShow" :text="loadingText"></loading>
        </div>

        <div v-transfer-dom>
            <x-dialog @on-hide="goAuth" v-model="showDialog" hide-on-blur :dialog-style="{'max-width': '100%', width: '100%', height: '50%', 'background-color': 'transparent'}">
                <p style="color:#fff;text-align:center;" @click="goAuth">
                    <x-button plain style="color:#fff;border-color: #fff;font-size:30px;">{{ this.showDialogText }}</x-button>
                </p>
            </x-dialog>
        </div>

    </div>
</template>

<script>
    /* eslint-disable */

    import { XButton, XInput, Group, XTextarea, Grid, GridItem, Previewer, TransferDom, Loading, XDialog, ButtonTab, ButtonTabItem, Flexbox, FlexboxItem } from 'vux'

    import server from '../config/server'
    import * as util from '../config/util'

    export default {
        directives: {
            TransferDom
        },
        name: 'enroll',
        data () {
            return {
                showDialog: false,
                showDialogText: '',
                loadingShow: false,
                loadingText: '上传中',
                currentProgress: 0,
                submitBtnText: '报名',
                submitBtnDisabled: false,
                resetBtnDisabled: false,
                uploadImgBtn: true,

                formData: {
                    sex: 0,
                    phone: '',
                    email: '',
                    intro: '',
                    author: '',
                    imgHash: []
                },
                imgCount: 0,
                imgList: [],
                options: {
                    getThumbBoundsFn (index) {
                        // find thumbnail element
                        let thumbnail = document.querySelectorAll('.previewer-img')[index]
                        // get window scroll Y
                        let pageYScroll = window.pageYOffset || document.documentElement.scrollTop
                        // optionally get horizontal scroll
                        // get position of element relative to viewport
                        let rect = thumbnail.getBoundingClientRect()
                        // w = width
                        return {x: rect.left, y: rect.top + pageYScroll, w: rect.width}
                        // Good guide on how to get element coordinates:
                        // http://javascript.info/tutorial/coordinates
                    }
                }
            }
        },
        components: {
            XInput,
            Group,
            XTextarea,
            Grid,
            GridItem,
            Previewer,
            Loading,
            XButton,
            XDialog,
            ButtonTab,
            ButtonTabItem,
            Flexbox,
            FlexboxItem
        },
        beforeRouteLeave (to, from, next) {
            this.showDialog = false
            this.loadingShow = false
            next()
        },
        beforeRouteEnter (to, from, next) {
            next(vm => {
                // 通过 `vm` 访问组件实例
                vm.$http.get(server.wechatAuthCheck).then(response => {
                    switch (response.data.errorCode) {
                        case 0:

                            break
                        case 10001:
                            vm.showDialog = true
                            vm.showDialogText = '点击进行微信授权'
                            break
                        default:
                            window.location.href = '/'
                            break

                    }

                })
            })
        },
        mounted () {

            this.$wechat.ready(function(){
                // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                console.log('aaaaaabbbbb')
            });

            this.$wechat.error(function(res){
                // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
                console.log('error: ' + res)
            });

            this.$http.get(server.enrollCheck).then(response => {
                if (response.data.errorCode === 0) {

                    this.$vux.alert.show({
                        title: '提示',
                        content: '你已经成功报名，可以查看你的报名信息'
                    })

                    this.submitBtnText = '已报名'
                    this.submitBtnDisabled = true
                    this.resetBtnDisabled = true
                    this.uploadImgBtn = false

                    this.formData = response.data.data
                    this.imgCount = this.formData.imgHash.length

                    for (var i = 0;i < this.imgCount; i++) {
                        this.imgList.push({src: server.qiniu + this.formData.imgHash[i]})
                    }

                }

            })

        },

        methods: {
            formSubmit () {
                this.$http.post(
                    server.enrollSubmit,
                    this.formData
                ).then(response => {

                    switch (response.data.errorCode) {
                        case 0:
                            this.$vux.alert.show({
                                title: '提示',
                                content: '报名成功，感谢您对比赛的支持！',
                                onHide () {
                                    location.reload()
                                }
                            })
                            break
                        case 10001:
                            vm.showDialog = true
                            vm.showDialogText = '点击进行微信授权'
                            break
                        case -2:
                            this.$vux.alert.show({
                                title: '错误',
                                content: '您已成功报名，请勿重复操作！',
                            })
                            break
                        default:
                            window.location.href = '/'
                            break

                    }

                })
            },
            resetForm () {
                this.formData = {
                    sex: 0,
                    phone: '',
                    email: '',
                    intro: '',
                    author: '',
                    imgHash: []
                }
                this.imgCount = 0
                this.imgList = []
            },
            goAuth () {
                var url = util.constructWechatAuth(encodeURIComponent(window.location.href))
                window.location.href = url
            },
            show (index) {
                this.$refs.previewer.show(index)
            },
            upload (event) {

                if (event.target.files.length === 0) {
                    return
                }

                if ((event.target.files.length + this.imgList.length) > 9) {
                    this.$vux.alert.show({
                        title: '提示',
                        content: '最多只能上传9张图片喔'
                    })
                    return
                }

                this.loadingShow = true

                if (event.target.files.length > 1){
                    this.loadingText = (this.currentProgress / event.target.files.length) * 100
                    this.loadingText += ' %'
                } else {
                    this.loadingText = '上传中'
                }

                for (var i = 0;i < event.target.files.length; i++) {

                    let file = event.target.files[i]
                    const self = this
                    const flag = this.flag
                    if (file) {
                        if (this.maxSize) {
                            // todo filter file
                        }
                        // filter file, 文件大小,类型等过滤
                        // 如果是图片文件
                        // const reader = new FileReader()
                        // const imageUrl = reader.readAsDataURL(file)
                        // img.src = imageUrl //在预览区域插入图片

                        const formData = new FormData()
                        formData.append('file', file)

                        // 获取token
                        this.$http.get(server.qiniuToken)
                            .then(response => {

                                const result = response.data
                                formData.append('token', result.data.token)
//                                formData.append('key', '/terry/' + i)
                                // 提交给七牛处理
                                self.$http.post('http://up-z2.qiniup.com', formData, {
                                    progress (event) {
                                        // 传递给父组件的progress方法
//                                    self.$emit('progress', parseFloat(event.loaded / event.total * 100), flag)
                                    }
                                })
                                    .then(response => {
                                        const result = response.data
                                        this.currentProgress++
                                        this.loadingText = Math.floor((this.currentProgress / event.target.files.length) * 100)
                                        this.loadingText += ' %'

                                        if (this.currentProgress === event.target.files.length) {
                                            this.loadingShow = false
                                            this.currentProgress= 0
                                        }

                                        this.imgCount++;
                                        var img = {}
                                        img.src = server.qiniu + result.key
                                        this.imgList.push(img)
                                        this.formData.imgHash.push(result.key)

                                    }, error => self.$emit('complete', 500, error.message), flag)
                            })
                    }

                }


            }
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    .uploader {
        position: absolute;
        z-index: 1;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    }

</style>
